package com.gframework.boot.mvc.controller.protocal.basic;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gframework.boot.mvc.controller.protocal.RestResponseHandler;

/**
 * 默认异常处理器，如果没有 {@code @ExceptionHandler} 注解细粒度声明的异常类型，那么就使用此异常处理器处理
 * 
 * @since 2.0.0
 * @author Ghwolf
 * @see BasicErrorController
 * @see ErrorMvcAutoConfiguration
 * @see RequestDispatcher
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class GFrameworkErrorController implements ErrorController {
	
	/**
	 * 前后端统一格式aop代理对象
	 */
	@Autowired
	private RestResponseHandler restResponseHandler;
	
	
	@RequestMapping
	@ResponseBody
	public Object error(HttpServletRequest request,HttpServletResponse response) {
		HttpStatus status = getStatus(request);
		return restResponseHandler.handleResult(status, request, response);
	}
	
	/**
	 * @see AbstractErrorController
	 */
	protected HttpStatus getStatus(HttpServletRequest request) {
		Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
		if (statusCode == null) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
		try {
			return HttpStatus.valueOf(statusCode);
		}
		catch (Exception ex) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
	}
	
	@Override
	public String getErrorPath() {
		return null;
	}
	
}